package com.gree.syq.wifidemo;

import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.SystemProperties;
import android.util.Log;

import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;

public class DemoApplication extends Application {
    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
        Log.i("DemoApplication", "static initializer: init successed");
    }

    private static String TAG = "DemoApplication";
    private static String role = "persist.wifidemo.role";

    private HandlerThread handlerThread = new HandlerThread("broad process");
    private Handler handler;
    private IntentFilter intentFilter = new IntentFilter();
    private DemoBroadReceiver receiver;

    public DemoRole mState = new DemoRole() {

        @Override
        public void init(Activity activity) {

        }

        @Override
        public void init() {

        }

        @Override
        public void run(String para) {

        }

        @Override
        public void onReceive(Context context, Intent intent) {

        }
    };

    class DemoBroadReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            mState.onReceive(context, intent);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper());

        Log.i(TAG, "onCreate: APP init");
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
        intentFilter.addAction(CONNECTIVITY_ACTION);

        receiver = new DemoBroadReceiver();
        registerReceiver(receiver, intentFilter,null,handler);

        Log.i(TAG, "onCreate: " + System.getProperty(role,"Air"));
        if(SystemProperties.get(role, "Air").equals("Air")){
            setState(2);
            mState = AirConditionRole.getInstance(getApplicationContext());
        } else {
            setState(1);
            mState = RemoteRole.getInstance(getApplicationContext());
        }
        mState.init();

        MessageP2P.getInstance(getApplicationContext()).onCreate();
    }

    private native void init();
    public native void setState(int state);
}
